package com.ycfmedical.bed.ui.fragment;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ycfmedical.bed.Constants;
import com.ycfmedical.bed.R;
import com.ycfmedical.bed.adapter.Vs_measureAdapter;
import com.ycfmedical.bed.listener.RefreshCallBack;
import com.ycfmedical.bed.present.VsmeasurePresenter;
import com.ycfmedical.bed.ui.BodyWeightShowActivity;
import com.ycfmedical.bed.ui.TemperatureShowActivity;
import com.ycfmedical.bed.utils.OnRecylerViewItemClickListener;
import com.ycfmedical.bed.utils.RefreshDataUtils;
import com.ycfmedical.bed.utils.ResourceUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.mvp.XFragment;
import cn.droidlover.xdroidmvp.router.Router;

/**
 * Created by Administrator on 2017-04-10.
 *
 */

public class VsmeasureFragment extends XFragment<VsmeasurePresenter> implements RefreshCallBack
{

    @BindView(R.id.weight_btn_back)
    Button weightBtnBack;

    @BindView(R.id.device_1)
    Button device1;

    @BindView(R.id.device_2)
    Button device2;

    @BindView(R.id.device_3)
    Button device3;

    @BindView(R.id.device_4)
    Button device4;

    @BindView(R.id.device_5)
    Button device5;

    @BindView(R.id.device_6)
    Button device6;

    @BindView(R.id.device_7)
    Button device7;

    @BindView(R.id.device_8)
    Button device8;

    @BindView(R.id.device_9)
    Button device9;

    @BindView(R.id.device_10)
    Button device10;

    @BindView(R.id.device_11)
    Button device11;

    @BindView(R.id.device_12)
    Button device12;

    @BindView(R.id.device_13)
    Button device13;

    @BindView(R.id.device_14)
    Button device14;

    @BindView(R.id.device_15)
    Button device15;

    @BindView(R.id.device_16)
    Button device16;

    @BindView(R.id.show_data_one)
    TextView showDataOne;

    @BindView(R.id.text_two)
    TextView textTwo;

    @BindView(R.id.text_three)
    TextView textThree;

    @BindView(R.id.layout_one)
    LinearLayout layoutOne;

    @BindView(R.id.show_data_two)
    TextView showDataTwo;

    @BindView(R.id.show_data_three)
    TextView showDataThree;

    @BindView(R.id.layout_two)
    LinearLayout layoutTwo;

    @BindView(R.id.device_debug)
    Button deviceDebug;

    @BindView(R.id.now_facility)
    Button nowFacility;

    @BindView(R.id.now_select_text)
    TextView nowSelectText;

    @BindView(R.id.text_show_temperature)
    TextView textShowTemperature;

    private RecyclerView recylerView;

    private List<TextView> datas;

    private String name, time;

    private int num;

    private Vs_measureAdapter adaprer;

    private String explain = "设备不可用";

    // 权限判断返回值
    final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
    private RefreshDataUtils refreshDataUtils;

    BluetoothAdapter mBluetoothAdapter;

    @Override
    public void initData(Bundle savedInstanceState)
    {
        // 初始化蓝牙权限问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            // SDK 版本大于23 android 6.0时进行处理
            initBluetoothPermissions();
        }

        Bundle bundle = getArguments();
        name = (String)bundle.get("name");
        time = (String)bundle.get("time");
        XLog.e("SJH", name + "" + time);
        _initView();
        _initRecDatas();
        // _initRec();

    }

    public void _initRec()
    {
        adaprer = new Vs_measureAdapter(context);
        GridLayoutManager manager = new GridLayoutManager(context, 4);
        recylerView.setLayoutManager(manager);
        recylerView.setAdapter(adaprer);
        recylerView.addOnItemTouchListener(new OnRecylerViewItemClickListener(recylerView)
        {
            @Override
            public void onItemClick(RecyclerView.ViewHolder vh)
            {
                XLog.e("SJH", "点击了" + vh.getAdapterPosition());
            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh)
            {

            }
        });
    }

    private void _initRecDatas()
    {
        datas = new ArrayList<TextView>();
        datas.add(device1);
        datas.add(device2);
        datas.add(device3);
        datas.add(device4);
        datas.add(device5);
        datas.add(device6);
        datas.add(device7);
        datas.add(device8);
        datas.add(device9);
        datas.add(device10);
        datas.add(device11);
        datas.add(device12);
        datas.add(device13);
        datas.add(device14);
        datas.add(device15);
        datas.add(device16);
        for (int i = 0; i < datas.size(); i++)
        {
            if (i > 9)
            {
                datas.get(i).setText("设备:" + (i + 1));
            } else {
                datas.get(i).setText("设备:" + (i + 1));
            }
        }
    }

    @Override
    public int getLayoutId()
    {
        return R.layout.fragment_vs_measure;
    }

    @Override
    public VsmeasurePresenter newP()
    {

        return new VsmeasurePresenter();
    }

    private void _initView()
    {
        refreshDataUtils = RefreshDataUtils.getRefreshDataUtils();
        refreshDataUtils.register(this);
        if (name.equals("Temperature"))
        {
            showDataOne.setText("当前检测温度");
            showDataTwo.setText("体温1");
            showDataThree.setText("体温2");
        }
        else if (name.equals("BodyWeight"))
        {
            showDataOne.setText("当前检测体重");
            showDataTwo.setText("体重1");
            showDataThree.setText("体重2");
            device2.setBackgroundResource(R.drawable.vs_measure);
            device2.setTextColor(Color.rgb(161, 161, 161));
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        refreshDataUtils.remove(this);
    }

    @OnClick({R.id.weight_btn_back, R.id.device_1, R.id.device_2, R.id.now_facility})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.weight_btn_back:
                getFragmentManager().popBackStackImmediate();
                break;
            case R.id.device_1:
                if (name.equals("Temperature"))
                {
                    // 选择体温枪1
                    nowSelectText.setText("一号体温枪");
                    judgeBluetoothState();
                    String TemperatureGunOneMac = "0F:03:16:92:20:4C";
                    String TpKeyOne = "TpKey";
                    Router.newIntent(getActivity())
                        .putString(TpKeyOne, TemperatureGunOneMac)
                        .to(TemperatureShowActivity.class)
                        .launch();
                }
                else if (name.equals("BodyWeight"))
                {
                    // 选择体重秤
                    nowSelectText.setText("一号体重秤");
                    judgeBluetoothState();
                    Router.newIntent(getActivity()).requestCode(Constants.RESULT_WEIGHT).to(BodyWeightShowActivity.class).launch();
                }
                break;
            case R.id.device_2:
                if (name.equals("Temperature"))
                {
                    nowSelectText.setText("二号体温枪");
                    String TemperatureGunTwoMac = "0F:03:16:92:20:E5";
                    String TpKeyTwo = "TpKey";
                    Router.newIntent(getActivity())
                        .putString(TpKeyTwo, TemperatureGunTwoMac)
                        .to(TemperatureShowActivity.class)
                        .launch();
                }
                break;
            case R.id.now_facility:
                // setTextData(data);
                break;
        }
    }

    /**
     * 设置数据方法
     */
    public void setTextData(String data)
    {
        textThree.setText(textTwo.getText());
        textTwo.setText(textShowTemperature.getText());
        textShowTemperature.setText(data);
    }

    /**
     * 判断设备蓝牙是否存在 判断蓝牙开启状态（未开启则自动开启）
     */

    private void judgeBluetoothState()
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null)
        {
            Toast.makeText(getContext(), R.string.bluetooth_remind, Toast.LENGTH_LONG).show();
            return;
        }
        if (!mBluetoothAdapter.isEnabled())
        {
            //自动开蓝牙
            mBluetoothAdapter.enable();
        }
    }
    @Override
    public void setData(int flag, String data) {
        XLog.e("SJH","flag"+flag+"data"+data);
        if(flag == Constants.BED_WEIGHT){
            //体重
                setTextData(data);
        }else if(flag == Constants.BED_TEMPERATURE){
            //体温
            setTextData(data);
        }
    }

    /**
     * 6.0以上蓝牙权限获取
     */
    private void initBluetoothPermissions()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            // SDK 版本大于23 android 6.0时进行处理
            // 判断是否有权限
            if (ContextCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            {
                // 请求权限
                ActivityCompat.requestPermissions(this.getActivity(),
                    new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
                    MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
                // 判断是否需要 向用户解释，为什么要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this.getActivity(),
                    Manifest.permission.READ_CONTACTS))
                {
                    Toast.makeText(getContext(), R.string.bluetooth_remind, Toast.LENGTH_SHORT).show();
                }
            }
        }
        else
        {
            // SDK 版本小于23，不管
        }

    }

    /**
     * 权限处理返回 6.0以上蓝牙权限获取
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //6.0权限获取成功

                } else {
                    //6.0权限获取失败
                    getvDelegate().toastShort(ResourceUtil.getResources().getString(R.string.bluetooth_permission_failure));
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
